package com.pai4j.pgc.service.community;
import com.fasterxml.jackson.core.type.TypeReference;
import com.pai4j.common.enums.CommonStatusEnum;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.common.util.RedisUtil;
import com.pai4j.domain.community.vo.response.cc.CTCNavPathNavListResponseVO;
import com.pai4j.domain.community.vo.response.cc.CTCNavResponseVO;
import com.pai4j.pgc.dao.community.ICCNavDAO;
import com.pai4j.pgc.dao.community.ICCNavPathDAO;
import com.pai4j.pgc.entity.community.CCNavEntity;
import com.pai4j.pgc.entity.community.CCNavPathEntity;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 *
 * @author: CYM-pai
 * @date: 2025/10/27 14:20
 **/
@Service
public class CCNavCoreCacheService {

    @Autowired
    private ICCNavPathDAO pathDAO;
    @Autowired
    private ICCNavDAO navDAO;
    @Autowired
    private RedisUtil redisUtil;

    /***
     * 查询导航核心数据
     * @return
     */
    public List<CTCNavPathNavListResponseVO> getCoreNavFromCache(Long ccid) {
        String redisKey = CTCRedisKeyEnum.CTC_NAV_CORE_CACHE.getKey(ccid.toString());
        if (!redisUtil.exists(redisKey)) {
            return this.refreshClientNavCache(ccid);
        }
        List<CTCNavPathNavListResponseVO> list = new ArrayList<>();
        String cache = redisUtil.get(redisKey);
        if (StringUtils.isNotBlank(cache)) {
            list = JsonUtil.fromJson(cache, new TypeReference<List<CTCNavPathNavListResponseVO>>() {});
        }
        return list;
    }

    /***
     * 刷新客户端导航缓存
     * @return
     */
    public List<CTCNavPathNavListResponseVO> refreshClientNavCache(Long ccid) {
        List<CTCNavPathNavListResponseVO> list = new ArrayList<>();
        // 查询导航
        List<CCNavPathEntity> pathEntityList =
                pathDAO.findAllByCcIdAndStatusInOrderByTagDescScoreDescIdAsc(ccid, Arrays.asList(CommonStatusEnum.PUBLISHED.getStatus()));
        if (CollectionUtils.isEmpty(pathEntityList)) {
            cleanCache(ccid);
            return Collections.emptyList();
        }
        // 查询导航下菜单
        Map<Long, List<CTCNavResponseVO>> pathNavMap = this.getAllNavMapFromDB(ccid);
        for (CCNavPathEntity path : pathEntityList) {
            CTCNavPathNavListResponseVO pathNav = this.convertPathNavVO(path);
            // 设置导航
            pathNav.setNavs(pathNavMap.getOrDefault(pathNav.getId(), Collections.emptyList()));
            list.add(pathNav);
        }
        // 刷新redis缓存
        redisUtil.set(CTCRedisKeyEnum.CTC_NAV_CORE_CACHE.getKey(ccid.toString()),
                         JsonUtil.toJsonString(list),
                         CTCRedisKeyEnum.CTC_NAV_CORE_CACHE.getExpireTime());
        return list;
    }

    /***
     * 查询全部有效导航，根据score倒序，id升序
     * @return
     */
    private Map<Long, List<CTCNavResponseVO>> getAllNavMapFromDB(Long ccid) {
        List<CCNavEntity> navEntityList = navDAO.queryCTCNavList(ccid, CommonStatusEnum.PUBLISHED.getStatus());
        if (CollectionUtils.isEmpty(navEntityList)) {
            return Collections.emptyMap();
        }
        Map<Long, List<CTCNavResponseVO>> pathNavMap = new HashMap<>();
        for (CCNavEntity nav : navEntityList) {
            Long pathId = nav.getPathId();
            List<CTCNavResponseVO> navList = pathNavMap.get(pathId);
            if (navList == null) {
                navList = new ArrayList<>();
                pathNavMap.put(pathId, navList);
            }
            navList.add(convertNavResponseVO(nav));
        }
        return pathNavMap;
    }

    private CTCNavPathNavListResponseVO convertPathNavVO(CCNavPathEntity pathEntity) {
        CTCNavPathNavListResponseVO pathNavListResponseVO = new CTCNavPathNavListResponseVO();
        pathNavListResponseVO.setId(pathEntity.getId());
        pathNavListResponseVO.setName(pathEntity.getName());
        pathNavListResponseVO.setShortName(pathEntity.getShortName());
        pathNavListResponseVO.setIcon(pathEntity.getIcon());
        pathNavListResponseVO.setTag(pathEntity.getTag());
        pathNavListResponseVO.setScore(pathEntity.getScore());
        pathNavListResponseVO.setStatus(pathEntity.getStatus());
        pathNavListResponseVO.setMenuType(pathEntity.getMenuType());
        return pathNavListResponseVO;
    }

    private CTCNavResponseVO convertNavResponseVO(CCNavEntity nav) {
        CTCNavResponseVO navResponseVO = new CTCNavResponseVO();
        BeanUtils.copyProperties(nav, navResponseVO);
        return navResponseVO;
    }

    /***
     * 清理缓存
     */
    private void cleanCache(Long ccid) {
        // 删除redis
        redisUtil.remove(CTCRedisKeyEnum.CTC_NAV_CORE_CACHE.getKey(ccid.toString()));
    }
}
